using System.Net.Http.Headers;

namespace YMJake.Flowable.ExternalWorker.Client.AspNetCore.Configuration;

/// <summary>
/// Configuration options for Flowable External Worker Client
/// </summary>
public class FlowableExternalWorkerOptions
{
    /// <summary>
    /// The base URL of the Flowable server
    /// </summary>
    public string FlowableHost { get; set; } = "https://trial.flowable.com/work";

    /// <summary>
    /// The worker ID to identify this worker instance
    /// </summary>
    public string? WorkerId { get; set; }

    /// <summary>
    /// Authentication header for the Flowable server
    /// </summary>
    public AuthenticationHeaderValue? Authentication { get; set; }

    /// <summary>
    /// Bearer token for Flowable Cloud authentication
    /// </summary>
    public string? BearerToken { get; set; }

    /// <summary>
    /// Basic authentication username
    /// </summary>
    public string? BasicAuthUsername { get; set; }

    /// <summary>
    /// Basic authentication password
    /// </summary>
    public string? BasicAuthPassword { get; set; }

    /// <summary>
    /// Custom HttpClient configuration
    /// </summary>
    public Action<HttpClient>? CustomizeClient { get; set; }

    /// <summary>
    /// HTTP timeout in seconds
    /// </summary>
    public int TimeoutSeconds { get; set; } = 30;
    
    /// <summary>
    /// Default number of concurrent workers per topic (default: 1)
    /// </summary>
    public int DefaultConcurrency { get; set; } = 1;

    /// <summary>
    /// Default polling interval in seconds (default: 30)
    /// </summary>
    public int DefaultPollingIntervalSeconds { get; set; } = 30;

    /// <summary>
    /// Default number of tasks to acquire in one batch (default: 1)
    /// </summary>
    public int DefaultNumberOfTasks { get; set; } = 1;

    /// <summary>
    /// Default number of retries for job acquisition (default: 5)
    /// </summary>
    public int DefaultNumberOfRetries { get; set; } = 5;

    /// <summary>
    /// Default lock duration for acquired jobs (default: PT5M)
    /// </summary>
    public string DefaultLockDuration { get; set; } = "PT5M";
    
    /// <summary>
    /// Validate and setup authentication
    /// </summary>
    internal void SetupAuthentication()
    {
        if (!string.IsNullOrEmpty(BearerToken))
        {
            Authentication = new AuthenticationHeaderValue("Bearer", BearerToken);
        }
        else if (!string.IsNullOrEmpty(BasicAuthUsername) && !string.IsNullOrEmpty(BasicAuthPassword))
        {
            var credentials = Convert.ToBase64String(
                System.Text.Encoding.ASCII.GetBytes($"{BasicAuthUsername}:{BasicAuthPassword}"));
            Authentication = new AuthenticationHeaderValue("Basic", credentials);
        }
    }
}